package com.learning.thread.base.volatileexample;

/**
 * ClassName: VolatileThread
 * Description: VolatileUse 简单使用
 * volatile 的意义在于在主线程中停止 InThread 线程，这 InThread 会立即发现 stop 状态的改变，从而停止
 * Date: 2018/7/2 10:49 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class VolatileThread {

    public static void main(String[] args) throws InterruptedException {
        InThread inThread = new InThread();
        new Thread(inThread, "Volatile Thread ").start();
        Thread.sleep(1000);
        inThread.stop();
        Thread.sleep(1000);
    }


    static class InThread implements Runnable {

        /**
         * 确保 stop 变量在多线程中可见
         */
        private volatile boolean stop = false;

        /**
         * 在其他线程中调用，停止本线程
         */
        public void stop() {
            this.stop = true;
        }

        @Override
        public void run() {
            int i = 0;
            while (!stop) {
                i++;
            }
            System.out.println("Stop Thread " + i);
        }
    }

}